package wj;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;

import wj.tree.WJNode;

public class Function {

	private String name;
	private ArrayList<String> parameters;
	private CommonTree blockTree;
	private WJNode blockNode;
	
    public Function(String name, ArrayList<String> parameters, CommonTree block) {
        this.name = name;
        this.parameters = parameters;
        this.blockTree = block;
    } 	
    
    public WJValue execute(ArrayList<WJValue> arguments, HashMap<String, Function> functions){
    	
    	Scope scope = new Scope(Scope.GLOBAL_SCOPE);
    	
    	for(int i=0; i < parameters.size(); i++)
    		scope.assign(parameters.get(i), arguments.get(i));
    	
    	 CommonTreeNodeStream nodes = new CommonTreeNodeStream(blockTree);
         WJTreeWalker walker = new WJTreeWalker(nodes, scope);
         try {
 			blockNode = walker.walk();
 			
 			return blockNode.evaluate();
 		} catch (RecognitionException e) {
 			System.out.println("Error executing function "+name+".");
 			e.printStackTrace();
 		}
    	
    	return WJValue.NULL;
    }
}
